package com.btm.dorisinfo.service;

import com.btm.dorisinfo.config.DynamicalConstant;
import com.btm.dorisinfo.model.TableInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DorisInfoExtractorService {

    private final JdbcTemplate jdbcTemplate;
    private final ObjectMapper objectMapper;
    private final Client meiliSearchClient;
    private final DynamicalConstant dynamicalConstant;

    public DorisInfoExtractorService(
            @Autowired JdbcTemplate jdbcTemplate,
            @Autowired ObjectMapper objectMapper,
            @Autowired Client meiliSearchClient,
            @Autowired DynamicalConstant dynamicalConstant
    ) {
        this.jdbcTemplate = jdbcTemplate;
        this.objectMapper = objectMapper;
        this.meiliSearchClient = meiliSearchClient;
        this.dynamicalConstant = dynamicalConstant;
    }

    /**
     * 获取指定数据库的所有表信息
     * @param databaseName 数据库名称
     * @return 表信息列表
     */
    public List<TableInfo> extractTableInfo(String databaseName) {
        log.info("开始提取数据库[{}]的表结构信息", databaseName);
        List<TableInfo> tableInfoList = new ArrayList<>();

        // 查询所有表
        String tableQuery = "SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES " +
                "WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME";
        List<Map<String, Object>> tables = jdbcTemplate.queryForList(tableQuery, databaseName);

        for (Map<String, Object> table : tables) {
            String tableSchema = (String) table.get("TABLE_SCHEMA");
            String tableName = (String) table.get("TABLE_NAME");
            String tableComment = (String) table.get("TABLE_COMMENT");

            // 查询表的列信息
            String columnQuery = "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, COLUMN_KEY, IS_NULLABLE, COLUMN_DEFAULT " +
                    "FROM INFORMATION_SCHEMA.COLUMNS " +
                    "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? " +
                    "ORDER BY ORDINAL_POSITION";
            List<Map<String, Object>> columns = jdbcTemplate.queryForList(columnQuery, tableSchema, tableName);

            List<TableInfo.ColumnInfo> columnInfoList = new ArrayList<>();
            for (Map<String, Object> column : columns) {
                TableInfo.ColumnInfo columnInfo = TableInfo.ColumnInfo.builder()
                        .columnName((String) column.get("COLUMN_NAME"))
                        .dataType((String) column.get("DATA_TYPE"))
                        .columnComment((String) column.get("COLUMN_COMMENT"))
                        .columnKey((String) column.get("COLUMN_KEY"))
                        .isNullable((String) column.get("IS_NULLABLE"))
                        .columnDefault(column.get("COLUMN_DEFAULT") != null ? column.get("COLUMN_DEFAULT").toString() : null)
                        .build();
                columnInfoList.add(columnInfo);
            }

            TableInfo tableInfo = TableInfo.builder()
                    .id(tableInfoList.size() + 1) // 设置自增id，从1开始
                    .tableSchema(tableSchema)
                    .tableName(tableName)
                    .tableComment(tableComment)
                    .columns(columnInfoList)
                    .build();

            tableInfoList.add(tableInfo);
        }

        log.info("成功提取数据库[{}]的表结构信息，共{}张表", databaseName, tableInfoList.size());
        return tableInfoList;
    }

    /**
     * 将表信息存储到MeiliSearch
     * @param tableInfoList 表信息列表
     * @return 存储结果
     */
    public String storeToMeiliSearch(List<TableInfo> tableInfoList) {
        try {
            log.info("开始将表结构信息存储到MeiliSearch，索引名：{}", dynamicalConstant.indexName);
            
            // 获取或创建索引
            Index index = meiliSearchClient.index(dynamicalConstant.indexName);
            
            // 使用TableInfo对象中的id字段作为文档ID
            for (int i = 0; i < tableInfoList.size(); i++) {
                TableInfo tableInfo = tableInfoList.get(i);
                // 将TableInfo转换为Map，使用对象自身的id字段
                String json = objectMapper.writeValueAsString(tableInfo);
                index.addDocuments(json);
                log.info("成功将表结构信息存储到MeiliSearch：{}", tableInfo.getTableName());
            }
            
            log.info("成功将{}张表的结构信息存储到MeiliSearch", tableInfoList.size());
            return String.format("成功将%d张表的结构信息存储到MeiliSearch", tableInfoList.size());
        } catch (MeilisearchException | JsonProcessingException e) {
            log.error("存储表结构信息到MeiliSearch失败", e);
            return "存储失败：" + e.getMessage();
        }
    }
}